package com.da.javatest.niuke.baodian;

import com.da.javatest.niuke.common.ListNode;

/**
 * @author chenlida
 * @date 2020/10/6 11:15
 * https://www.nowcoder.com/practice/ed85a09f0df047119e94fb3e5569855a?tpId=8&tags=&title=&diffculty=0&judgeStatus=0&rp=1
 */
public class C12Plus {
    public ListNode plusAB(ListNode a, ListNode b) {
        ListNode ret = b;
        while (a != null) {
            b.val += a.val;
            if (b.val >= 10) {
                b.val %= 10;
                if (b.next == null) {
                    b.next = new ListNode(1);
                } else {
                    b.next.val++;
                }
            }
            if (b.next == null) {
                b.next = a.next;
                break;
            }
            a = a.next;
            b = b.next;

        }
        return ret;
    }

    public ListNode plusAB2(ListNode a, ListNode b) {
        if (a == null || b == null) {
            return b == null ? a : b;
        }
        b.next = plusAB2(a.next, b.next);
        b.val += a.val;
        addUp(b, b.next);
        return b;
    }

    private void addUp(ListNode b, ListNode node) {
        if (b.val >= 10) {
            b.val %= 10;
            if (node == null) {
                b.next = node = new ListNode(1);
            } else {
                node.val++;
            }
            addUp(node, node.next);
        }
    }
}
